<?php

namespace App\Http\Middleware;

use App\Models\IpTableModel;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckIpMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $ip = IpTableModel::query()->get()->toArray();
        $allowedIps = [];
        foreach ($ip as $v) {
            $allowedIps[] = long2ip($v['ip']);
        }

        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
        if (!in_array($ip, array_merge($allowedIps, __('l.IP')))) {
            return response('Access Denied.', 403);
        }
        return $next($request);
    }
}
